import mqtt from "mqtt";


var client
const options = {
	// host: '127.0.0.1',
	// port: 8083,
	// endpoint: '/mqtt',
	clean: true, // 保留会话
	connectTimeout: 1000, // 超时时间
	reconnectPeriod: 1000, // 重连时间间隔
	// 认证信息
	// clientId: '1',
    clientId: "mqttjs_3be2c321" + new Date().getTime(),
	username: 'admin',
	password: 'admin',
}
var result;
export function mqttConnection(clientDict) {
	// console.log(122)

	options.username = clientDict.username
	options.password = clientDict.password

	// "ws://127.0.0.1:9001/mqtt"
	// console.log(clientDict)
	var clientAddr = `wss://${clientDict.host}:${clientDict.port}/mqtt`
	console.log(clientAddr)
	client = mqtt.connect(clientAddr, options)
	client.on('connect', (e) => {
		// console.log(e);
		console.log('mqtt连接成功');
		// client.subscribe('testtopic', {
		// 	qos: 0
		// }, (error) => { //订阅指定主题testtopic
		// 	// client.subscribe('#',{qos:0},(error)=>{//订阅全部主题testtopic
		// 	console.log(error)
		// 	if (!error) {
		// 	  console.log('订阅成功')
		// 	} else {
		// 	  console.log('订阅失败')
		// 	}
		// })
	});
	client.on('message', (testtopic, message) => {
		console.log(message)
		// let xx = '收到来自' + testtopic + '的消息' + message;

	})
	client.on('reconnect', (error) => {
		console.log('正在重连')
	})
	client.on('disconnect', (error) => {
		console.log('服务器断开',error)
	})
	client.on('error', (error) => {
		console.log('链接失败',error)
	})
	client.on('close', (error) => {
		client.end()
	})
}

export function sendMqttMsg(topic, content){
    client.publish(topic, content)
}

export function destroyConnection(){
//   client.unsubscribe('testtopic');
}
